// Protocol Buffers for GWT
// Copyright 2010 Thomas Broyer  All rights reserved.
// http://code.google.com/p/protobuf-gwt/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package net.ltgt.gwt.protobuf.compiler.client;

import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.compiler.JavaHelpers;

import java.io.IOException;
import java.io.Writer;

/**
 * @author t.broyer@ltgt.net Thomas Broyer
 * Based on the initial work of:
 * @author kenton@google.com Kenton Varda
 * Based on original Protocol Buffers design by
 * Sanjay Ghemawat, Jeff Dean, and others.
 */
public class PrimitiveFieldGenerator extends SingularFieldGenerator {

  public PrimitiveFieldGenerator(FieldDescriptor descriptor) {
    super(descriptor, JavaHelpers.getPrimitiveTypeName(descriptor.getJavaType()),
        JavaHelpers.getBoxedPrimitiveTypeName(descriptor.getJavaType()));
  }

  @Override
  public void generateBuilderMembers(Writer output) throws IOException {
    output.write("public boolean has" + capitalizedName + "() { return result.has" + capitalizedName + "(); }\n");
    output.write("public " + typeName + " get" + capitalizedName + "() { return result.get" + capitalizedName + "(); }\n");
    output.write("public Builder set" + capitalizedName + "(" + typeName + " value) {\n");
    // FIXME: make a "is reference type" method
    if (typeName.equals(boxedTypeName)) {
      output.write("  if (value == null) { throw new NullPointerException(); }\n");
    }
    output.write("  result." + name + "_ = value;\n");
    output.write("  result.has" + capitalizedName + "_ = true;\n");
    output.write("  return this;\n");
    output.write("}\n");
    output.write("public Builder clear" + capitalizedName + "() {\n");
    output.write("  result." + name + "_ = getDefaultInstance().get" + capitalizedName + "();\n");
    output.write("  result.has" + capitalizedName + "_ = false;\n");
    output.write("  return this;\n");
    output.write("}\n");
  }

  @Override
  public void generateMembers(Writer output) throws IOException {
    output.write("private boolean has" + capitalizedName + "_;\n");
    output.write("private " + typeName + " " + name + "_ = " + getDefaultValue() + ";\n");
    output.write("public boolean has" + capitalizedName + "() { return has" + capitalizedName + "_; }\n");
    output.write("public " + typeName + " get" + capitalizedName + "() { return " + name + "_; }\n");
  }

  @Override
  public void generateParsingCode(Writer output) throws IOException {
    output.write("case " + descriptor.getNumber() + ":\n");
    switch (descriptor.getJavaType()) {
      case INT:
        output.write("  set" + capitalizedName + "(streamReader.readInt());\n");
        break;
      case LONG:
        output.write("  set" + capitalizedName + "(streamReader.readLong());\n");
        break;
      case FLOAT:
        output.write("  set" + capitalizedName + "(streamReader.readFloat());\n");
        break;
      case DOUBLE:
        output.write("  set" + capitalizedName + "(streamReader.readDouble());\n");
        break;
      case BOOLEAN:
        output.write("  set" + capitalizedName + "(streamReader.readBoolean());\n");
        break;
      case STRING:
        output.write("  set" + capitalizedName + "(streamReader.readString());\n");
        break;
      case BYTE_STRING:
        output.write("  set" + capitalizedName + "(\n");
        output.write("    com.google.protobuf.ByteString_CustomFieldSerializer.instantiate(streamReader));\n");
        // FIXME: we know deserialize is a noop, but we could make this better overall
        break;
      case ENUM:
      case MESSAGE:
      default:
        throw new IllegalArgumentException();
    }
    output.write("  break;\n");
  }

  @Override
  public void generateSerializationCode(Writer output) throws IOException {
    output.write("if (has" + capitalizedName + "()) {\n");
    output.write("  streamWriter.writeInt(" + descriptor.getNumber() + ");\n");
    switch (descriptor.getJavaType()) {
      case INT:
        output.write("  streamWriter.writeInt(get" + capitalizedName + "());\n");
        break;
      case LONG:
        output.write("  streamWriter.writeLong(get" + capitalizedName + "());\n");
        break;
      case FLOAT:
        output.write("  streamWriter.writeFloat(get" + capitalizedName + "());\n");
        break;
      case DOUBLE:
        output.write("  streamWriter.writeDouble(get" + capitalizedName + "());\n");
        break;
      case BOOLEAN:
        output.write("  streamWriter.writeBoolean(get" + capitalizedName + "());\n");
        break;
      case STRING:
        output.write("  streamWriter.writeString(get" + capitalizedName + "());\n");
        break;
      case BYTE_STRING:
        output.write("  com.google.protobuf.ByteString_CustomFieldSerializer.serialize(streamWriter, get" + capitalizedName + "());\n");
        break;
      case ENUM:
      case MESSAGE:
      default:
        throw new IllegalArgumentException();
    }
    output.write("}\n");
  }

  @Override
  public void generateDescriptorCode(Writer output) throws IOException {
    output.write("new com.google.protobuf.Descriptors.PrimitiveFieldDescriptor(this,\n");
    output.write("    \"" + descriptor.getName() + "\", " + descriptor.getNumber() + ", " + descriptor.getIndex() + ", " + descriptor.isRequired() + ",\n");
    output.write("    com.google.protobuf.Descriptors.FieldDescriptor.Type." + descriptor.getType().name() + ", " +
        (descriptor.hasDefaultValue() ? getDefaultValue() : "null") + "),\n");
  }
  
  private String getDefaultValue() {
    switch (descriptor.getJavaType()) {
      case INT:
        return descriptor.getDefaultValue().toString();
      case LONG:
        return ((Long) descriptor.getDefaultValue()).toString() + "L";
      case FLOAT: {
        float f = (Float) descriptor.getDefaultValue();
        if (f == Float.POSITIVE_INFINITY) {
          return "Float.POSITIVE_INFINITY";
        } else if (f == Float.NEGATIVE_INFINITY) {
          return "Float.NEGATIVE_INFINITY";
        } else if (Float.isNaN(f)) {
          return "Float.NaN";
        } else {
          return f + "F";
        }
      }
      case DOUBLE: {
        double d = (Double) descriptor.getDefaultValue();
        if (d == Double.POSITIVE_INFINITY) {
          return "Double.POSITIVE_INFINITY";
        } else if (d == Double.NEGATIVE_INFINITY) {
          return "Double.NEGATIVE_INFINITY";
        } else if (Double.isNaN(d)) {
          return "Double.NaN";
        } else {
          return Double.toString(d);
        }
      }
      case BOOLEAN:
        return descriptor.getDefaultValue().toString();
      case STRING: {
        String s = (String) descriptor.getDefaultValue();
        StringBuilder ret = new StringBuilder("\"");
        for (int i = 0, l = s.length(); i < l; i++) {
          ret.append('\\');
          char c = s.charAt(i);
          switch (c) {
            case '"':
            case '\\':
              ret.append(c);
              break;
            case '\n':
              ret.append('n');
              break;
            case '\r':
              ret.append('r');
              break;
            default: {
              String hex = Integer.toHexString(c);
              ret.append('u').append("0000", 0, 4 - hex.length()).append(hex);
              break;
            }
          }
        }
        ret.append('"');
        return ret.toString();
      }
      case BYTE_STRING:
        if (descriptor.hasDefaultValue()) {
          ByteString bs = (ByteString) descriptor.getDefaultValue();
          StringBuilder ret = new StringBuilder(
              "com.google.protobuf.Internal.bytesDefaultValue(\"");
          // special-case LineTerminators and other non-StringCharacters per JLS
          // http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5
          for (int i = 0, l = bs.size(); i < l; i++) {
            ret.append('\\');
            byte b = bs.byteAt(i);
            switch (b) {
              case '"':
              case '\\':
                ret.append((char) b);
                break;
              case '\n':
                ret.append('n');
                break;
              case '\r':
                ret.append('r');
                break;
              default:
                ret.append(Integer.toOctalString(b & 0xff));
                break;
            }
          }
          ret.append("\")");
          return ret.toString();
        } else {
          return "com.google.protobuf.ByteString.EMPTY";
        }
      case ENUM:
      case MESSAGE:
      default:
        throw new IllegalArgumentException();
    }
  }
}
